using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
using AF.Data;
using AF.Models;

namespace AF.Activities
{
    [Activity(Label = "添加记录", Theme = "@android:style/Theme.Material.Light.NoActionBar")]
    public class AddTransactionActivity : Activity
    {
        private DatabaseHelper? dbHelper;
        private RadioGroup? radioGroupType;
        private EditText? editAmount;
        private Spinner? spinnerCategory;
        private Spinner? spinnerProject;
        private Button? btnSelectDate;
        private EditText? editDescription;
        private EditText? editRemark;
        private Button? btnSave;
        private Button? btnCancel;

        private List<Category> categories = new List<Category>();
        private List<Project> projects = new List<Project>();
        private DateTime selectedDate = DateTime.Now;
        private TransactionType currentType = TransactionType.Expense;

        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_add_transaction);

            dbHelper = new DatabaseHelper(this);

            InitializeViews();
            SetupEventHandlers();
            LoadCategories();
            LoadProjects();
        }

        private void InitializeViews()
        {
            radioGroupType = FindViewById<RadioGroup>(Resource.Id.radioGroupType);
            editAmount = FindViewById<EditText>(Resource.Id.editAmount);
            spinnerCategory = FindViewById<Spinner>(Resource.Id.spinnerCategory);
            spinnerProject = FindViewById<Spinner>(Resource.Id.spinnerProject);
            btnSelectDate = FindViewById<Button>(Resource.Id.btnSelectDate);
            editDescription = FindViewById<EditText>(Resource.Id.editDescription);
            editRemark = FindViewById<EditText>(Resource.Id.editRemark);
            btnSave = FindViewById<Button>(Resource.Id.btnSave);
            btnCancel = FindViewById<Button>(Resource.Id.btnCancel);

            // 设置默认日期
            btnSelectDate!.Text = selectedDate.ToString("yyyy年MM月dd日");

            // 检查是否是编辑模式
            int transactionId = Intent?.GetIntExtra("transaction_id", -1) ?? -1;
            if (transactionId != -1)
            {
                var titleView = FindViewById<TextView>(Resource.Id.textTitle);
                if (titleView != null)
                    titleView.Text = "编辑记录";
            }
        }

        private void SetupEventHandlers()
        {
            if (radioGroupType != null)
            {
                radioGroupType.CheckedChange += (s, e) =>
                {
                    currentType = e.CheckedId == Resource.Id.radioIncome 
                        ? TransactionType.Income 
                        : TransactionType.Expense;
                    LoadCategories();
                };
            }

            if (spinnerProject != null)
            {
                spinnerProject.ItemSelected += (s, e) =>
                {
                    // 如果选择了"+ 新建项目"选项（最后一项）
                    if (e.Position == spinnerProject.Adapter!.Count - 1)
                    {
                        ShowQuickAddProject();
                    }
                };
            }

            if (btnSelectDate != null)
            {
                btnSelectDate.Click += (s, e) => ShowDatePicker();
            }

            if (btnSave != null)
            {
                btnSave.Click += (s, e) => SaveTransaction();
            }

            if (btnCancel != null)
            {
                btnCancel.Click += (s, e) => Finish();
            }
        }

        private void LoadCategories()
        {
            if (dbHelper == null || spinnerCategory == null) return;

            categories = dbHelper.GetCategoriesByType(currentType);
            
            var categoryNames = categories.Select(c => c.Icon + " " + c.Name).ToList();
            var adapter = new ArrayAdapter<string>(this, 
                Android.Resource.Layout.SimpleSpinnerItem, categoryNames);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinnerCategory.Adapter = adapter;
        }

        private void ShowDatePicker()
        {
            var datePickerDialog = new DatePickerDialog(
                this,
                (s, e) =>
                {
                    selectedDate = e.Date;
                    if (btnSelectDate != null)
                        btnSelectDate.Text = selectedDate.ToString("yyyy年MM月dd日");
                },
                selectedDate.Year,
                selectedDate.Month - 1,
                selectedDate.Day
            );
            datePickerDialog.Show();
        }

        private void SaveTransaction()
        {
            if (dbHelper == null) return;

            // 验证输入
            if (string.IsNullOrWhiteSpace(editAmount?.Text))
            {
                Toast.MakeText(this, "请输入金额", ToastLength.Short)?.Show();
                return;
            }

            if (!decimal.TryParse(editAmount?.Text, out decimal amount) || amount <= 0)
            {
                Toast.MakeText(this, "请输入有效的金额", ToastLength.Short)?.Show();
                return;
            }

            if (spinnerCategory?.SelectedItemPosition < 0 || 
                spinnerCategory?.SelectedItemPosition >= categories.Count)
            {
                Toast.MakeText(this, "请选择分类", ToastLength.Short)?.Show();
                return;
            }

            var selectedCategory = categories[spinnerCategory!.SelectedItemPosition];

            // 获取选择的项目（如果有）
            int? projectId = null;
            string? projectName = null;
            if (spinnerProject != null && spinnerProject.SelectedItemPosition > 0)
            {
                int selectedPosition = spinnerProject.SelectedItemPosition;
                
                // 检查是否选择了"+ 新建项目"（最后一项）
                if (selectedPosition == spinnerProject.Adapter!.Count - 1)
                {
                    Toast.MakeText(this, "请先创建项目", ToastLength.Short)?.Show();
                    return;
                }
                
                // 正常的项目选择（索引-1，因为第一项是"不关联项目"）
                var selectedProject = projects[selectedPosition - 1];
                projectId = selectedProject.Id;
                projectName = selectedProject.Name;
            }

            var transaction = new Transaction
            {
                Type = currentType,
                Amount = amount,
                CategoryId = selectedCategory.Id,
                CategoryName = selectedCategory.Name,
                ProjectId = projectId,
                ProjectName = projectName,
                Description = editDescription?.Text ?? "",
                Date = selectedDate,
                Remark = editRemark?.Text
            };

            long result = dbHelper.AddTransaction(transaction);

            if (result > 0)
            {
                Toast.MakeText(this, "保存成功", ToastLength.Short)?.Show();
                SetResult(Result.Ok);
                Finish();
            }
            else
            {
                Toast.MakeText(this, "保存失败", ToastLength.Short)?.Show();
            }
        }

        private void LoadProjects()
        {
            if (dbHelper == null || spinnerProject == null) return;

            projects = dbHelper.GetAllProjects()
                .Where(p => p.Status == ProjectStatus.InProgress)
                .ToList();
            
            var projectNames = new List<string> { "不关联项目" };
            projectNames.AddRange(projects.Select(p => $"📁 {p.Name}"));
            projectNames.Add("➕ 新建项目");  // 添加新建项目选项
            
            var adapter = new ArrayAdapter<string>(this, 
                Android.Resource.Layout.SimpleSpinnerItem, projectNames);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinnerProject.Adapter = adapter;
        }

        private void ShowQuickAddProject()
        {
            // 创建输入框布局
            var inputLayout = new LinearLayout(this)
            {
                Orientation = Orientation.Vertical
            };
            inputLayout.SetPadding(50, 20, 50, 20);

            // 项目名称输入
            var editProjectName = new EditText(this)
            {
                Hint = "请输入项目名称"
            };
            inputLayout.AddView(editProjectName);

            // 客户名称输入
            var editClientName = new EditText(this)
            {
                Hint = "客户名称（可选）"
            };
            editClientName.SetPadding(0, 20, 0, 0);
            inputLayout.AddView(editClientName);

            var dialog = new AlertDialog.Builder(this)!
                .SetTitle("快速创建项目")!
                .SetView(inputLayout)!
                .SetPositiveButton("创建", (s, e) =>
                {
                    string projectName = editProjectName.Text?.Trim() ?? "";
                    
                    if (string.IsNullOrWhiteSpace(projectName))
                    {
                        Toast.MakeText(this, "请输入项目名称", ToastLength.Short)?.Show();
                        // 重置下拉框到"不关联项目"
                        if (spinnerProject != null)
                            spinnerProject.SetSelection(0);
                        return;
                    }

                    // 创建新项目
                    var newProject = new Project
                    {
                        Name = projectName,
                        ClientName = editClientName.Text?.Trim(),
                        Description = "",
                        Status = ProjectStatus.InProgress,
                        StartDate = DateTime.Now
                    };

                    if (dbHelper != null)
                    {
                        long projectId = dbHelper.AddProject(newProject);
                        
                        if (projectId > 0)
                        {
                            Toast.MakeText(this, "项目创建成功", ToastLength.Short)?.Show();
                            
                            // 重新加载项目列表
                            LoadProjects();
                            
                            // 自动选择新创建的项目
                            if (spinnerProject != null)
                            {
                                // 新项目在倒数第二个位置（最后一个是"+ 新建项目"）
                                spinnerProject.SetSelection(projects.Count);
                            }
                        }
                        else
                        {
                            Toast.MakeText(this, "项目创建失败", ToastLength.Short)?.Show();
                            if (spinnerProject != null)
                                spinnerProject.SetSelection(0);
                        }
                    }
                })!
                .SetNegativeButton("取消", (s, e) =>
                {
                    // 重置下拉框到"不关联项目"
                    if (spinnerProject != null)
                        spinnerProject.SetSelection(0);
                })!
                .SetOnCancelListener(new DialogCancelListener(() =>
                {
                    // 对话框取消时重置
                    if (spinnerProject != null)
                        spinnerProject.SetSelection(0);
                }))!
                .Create();

            dialog?.Show();
        }
    }

    // 对话框取消监听器
    public class DialogCancelListener : Java.Lang.Object, IDialogInterfaceOnCancelListener
    {
        private readonly Action onCancel;

        public DialogCancelListener(Action onCancel)
        {
            this.onCancel = onCancel;
        }

        public void OnCancel(IDialogInterface? dialog)
        {
            onCancel?.Invoke();
        }
    }
}

